<template>
    <a-row>
        <a-col :span="18">
            <tableLayout :columns="columns" :page="false" :get="getData" :rowKey="Id" ref="layout"
                :selectItem="selectItem" v-on:change="tableOnChange"
                :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
                <template v-slot:status="item">
                    测试-{{ item.value.text.name }}
                </template>
                <template #button>
                    <a-button type="primary" style="margin-left: 20px" @click='add'>新增</a-button>
                    <a-button style="margin-left: 20px" @click="edit"
                        :disabled="selectedRowKeys.length !== 1">修改</a-button>
                    <a-button type="primary" style="margin-left: 20px" @click="del"
                        :disabled="selectedRowKeys.length !== 1" danger>删除</a-button>
                </template>
                <template #operationMore="item">
                    <a @click="edit(null, item.value.record)">编辑</a>
                    <a-divider type="vertical" />
                    <a @click="del(null, item.value.record.Id)">删除</a>
                </template>
                <template v-slot:custom="data">
                    <a-input v-model:value="data.formData[data.key]" />
                </template>
            </tableLayout>
        </a-col>
        <a-col :span="6">
            <div style="height:400px;">
                <vue3-tree-org :data="orgata" :props="{id: 'Id', pid: 'ParentId', label: 'Name',children: 'children' }" center :horizontal="false" :collapsable="true" :label-style="style"
                    :only-one-node="false" :clone-node-drag="true" :before-drag-end="beforeDragEnd"
                    @on-node-drag="nodeDragMove" @on-node-drag-end="nodeDragEnd" @on-contextmenu="onMenus"
                    @on-expand="onExpand" @on-node-dblclick="onNodeDblclick" @on-node-click="onNodeClick" />
            </div>
        </a-col>
    </a-row>

    <a-modal :title="formState.Id ? '编辑部门' : '新增部门'" v-model:visible="model_visible" :confirm-loading="confirmLoading"
        @ok="model_handleOk" width="900px">
        <a-form ref="formRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules"
            layout="inline" class="comform">
            <a-form-item label="部门名称" style="width: calc(50% - 20px);" class="form__item" name="Name">
                <a-input v-model:value="formState.Name" />
            </a-form-item>
            <a-form-item label="上级部门" style="width: calc(50% - 20px);" class="form__item" name="ParentId">
                <a-tree-select v-model:value="formState.ParentId" style="width: 100%"
                    :replaceFields="{ children: 'children', title: 'Name', key: 'Id', value: 'Id' }"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="treeData"
                    placeholder="Please select" tree-default-expand-all />
            </a-form-item>
            <a-form-item label="负责人名称" style="width: calc(50% - 20px);" class="form__item" name="Director">
                <a-input v-model:value="formState.Director" />
            </a-form-item>
            <a-form-item label="负责人" style="width: calc(50% - 20px);" class="form__item" name="DirectorId">
                <a-select v-model:value="formState.DirectorId" style="width: 100%;" @change="directorChange">
                    <a-select-option v-for="item in userOptions" :key="item.Id" :value="item.Id">
                        {{ item.RealName }}
                    </a-select-option>

                </a-select>
            </a-form-item>
            <a-form-item label="电话号码" style="width: calc(50% - 20px);" class="form__item" name="Phone">
                <a-input v-model:value="formState.Phone" />
            </a-form-item>
            <a-form-item label="邮箱" style="width: calc(50% - 20px);" class="form__item" name="Email">
                <a-input v-model:value="formState.Email" />
            </a-form-item>
            <a-form-item label="状态" style="width: calc(50% - 20px);" class="form__item" name="IsValid">
                <a-radio-group name="radioGroup" v-model:value="formState.IsValid">
                    <a-radio :value="1">启用</a-radio>
                    <a-radio :value="0">停用</a-radio>
                </a-radio-group>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script lang="ts" setup>
import { getData, delDepartment, setDepartment, getAllUserData } from '@/api/syssetting/department';
import { defineComponent, ref, onMounted, onBeforeMount, nextTick, UnwrapRef, reactive, h, VNode } from 'vue';
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { Layout, message } from 'ant-design-vue';
import { DepartmentInput } from '@/types/api/syssetting/department';


const layout = ref();
const userOptions = ref([]);

onBeforeMount(() => {
    loadTreeData();
    loadAllUser();
})

const loadAllUser = () => {
    getAllUserData({}).then(e => {
        userOptions.value = e.data.Data;
    }).catch(err => {
        message.error(err.message || "获取用户列表失败!");
    });
}

const loadTreeData = () => {
    getData({ MenuType: 1 }).then(e => {
        treeData.value = e.data.Data;
        if(treeData.value.length>0){
            orgata.value = treeData.value[0];
        }
    }).catch(err => {
        message.error(err.message || "获取部门列表失败!");
    });
}
const style = {
    // background: "#fff",
    // color: "#5e6d82",
    color: "#fff", background: "#108ffe"
}
// const data = ref({
//     "id": 1, "label": "xxx科技有限公司",
//     "children": [
//         {
//             "id": 2, "pid": 1, "label": "产品研发部",
//             "style": { "color": "#fff", "background": "#108ffe" },
//             "children": [
//                 { "id": 6, "pid": 2, "label": "禁止编辑节点", "disabled": true },
//                 { "id": 8, "pid": 2, "label": "禁止拖拽节点", "noDragging": true },
//                 { "id": 10, "pid": 2, "label": "测试" }
//             ]
//         },
//         {
//             "id": 3, "pid": 1, "label": "客服部",
//             "children": [
//                 { "id": 11, "pid": 3, "label": "客服一部" },
//                 { "id": 12, "pid": 3, "label": "客服二部" }
//             ]
//         },
//         { "id": 4, "pid": 1, "label": "业务部" }
//     ]
// });

const onMenus = ({ node, command }) => {
    console.log(node, command);
}

const onExpand = (e: any, data: any) => {
    console.log(e, data);
}

const onExpandAll = (b: any) => {
    console.log(b)
}
const nodeDragMove = (data: any) => {
    console.log(data);
}

const beforeDragEnd = (node: any, targetNode: any) => {
    return new Promise((resolve, reject) => {
        if (!targetNode) reject()
        if (node.id === targetNode.id) {
            reject()
        } else {
            resolve()
        }
    })
}

const nodeDragEnd = (data: any, isSelf: any) => {
    console.log(data, isSelf);
}

const onNodeDblclick = () => {
    console.log('onNodeDblclick')
}
const onNodeClick = (e: any, data: any) => {
    console.log(data.label);
}
const expandChange = () => {
    // this.toggleExpand(this.data, this.expandAll);
}
const toggleExpand = (data: any, val: any) => {
    if (Array.isArray(data)) {
        data.forEach((item) => {
            item.expand = val
            if (item.children) {
                toggleExpand(item.children, val);
            }
        });
    } else {
        data.expand = val
        if (data.children) {
            toggleExpand(data.children, val);
        }
    }
}

const directorChange = (e: any) => {
    debugger
    let user = userOptions.value.find(x => x.Id == e);
    formState.Director = user.RealName;
    formState.Email = user.Email;
    formState.Phone = user.Mobile;
}

//列表
const columns = [
    { title: '名称', dataIndex: 'Name' },
    { title: '负责人', dataIndex: 'Director' },
    { title: '邮箱', dataIndex: 'Email' },
    { title: '电话', dataIndex: 'Phone' },
    { title: '排序', dataIndex: 'SortNum' },
    {
        title: '状态', dataIndex: 'IsValid', customRender: function ({ text }): VNode {
            return h('div', {
                style: {
                    color: 'red'
                }
            }, text ? '有效' : '无效');
        }
    }
]

// 筛选
const selectItem = ref([
    { title: '名称', key: 'Name', type: 'input', itemWidth: '290px' }
])

// 规则
const rules = {
    Name: [{ required: true, message: '请输入名称', trigger: 'change' }],
    Director: [{ required: true, message: '请输入负责人', trigger: 'change' }],
    Phone: [{ required: true, message: '请输入链接', trigger: 'change' }]
}

const treeData = ref([]);
const orgata = ref({});

const tableOnChange = (e: any) => {
    let dataSource = layout.value.dataSource;
    treeData.value = dataSource;
}

//表单对象
const formState: UnwrapRef<DepartmentInput> = reactive({
    Id: '',
    ParentId: '',
    Name: '',
    Email: '',
    Director: '',
    SortNum: 0,
    Phone: '',
    DirectorId: '',
    IsValid: false
});

const add = () => {
    model_visible.value = true;
    Object.assign(formState, {
        Id: '',
        ParentId: '',
        Name: '',
        Director: '',
        SortNum: 0,
        Phone: '',
        Email: '',
        DirectorId: '',
        IsValid: false
    });
}

const edit = (event: any, item: any) => {
    let selectItem = item;
    if (!item) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectItem = selectedRows.value[0];
    }
    model_visible.value = true;
    Object.assign(formState, selectItem);
}

const del = (event: any, Id: any) => {
    let selectId = Id;
    if (!selectId) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectId = selectedRows.value[0].Id;
    }

    delDepartment({ Id: selectId }).then(() => {
        message.success("删除成功!");
        layout.value.getData();
    }).catch(err => {
        message.error(err.message || "删除失败!")
        confirmLoading.value = false;
    })
}

const model_visible = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const formRef = ref()

const model_handleOk = () => {
    formRef.value.validate().then(() => {
        confirmLoading.value = true;
        setDepartment(formState).then(e => {
            message.success("添加成功！");
            confirmLoading.value = false;
            model_visible.value = false;
            layout.value.getData();
            loadTreeData();
        }).catch(err => {
            message.error(err.message || "添加失败!")
            confirmLoading.value = false;
        })
    }).catch(() => {
        message.error('请检查必填项是否全部填写!');
    })
}

// 多选
const selectedRowKeys = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const onSelectChange = (keys: [], rows: any) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
}


const labelCol = { span: 6 };
const wrapperCol = { span: 18 };

</script>

<style lang="scss" scoped>
.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1 !important;
            flex-shrink: 0;
        }
    }
}
</style>
<style lang="scss">
.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1;
            flex-shrink: 0;
        }
    }
}
</style>